package com.norrielm.GooglePlusPosts;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Scanner;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.widget.ListAdapter;

import com.norrielm.GooglePlusPosts.models.Post;
import com.norrielm.GooglePlusPosts.models.Receiver;

/**
 * Queries Google+ and loads results into an {@link Adapter}.
 * 
 * @author Lauren Norrie (norrielm)
 */
public class GooglePlusPresenter {

	private final static String APPS_URL = "https://www.googleapis.com/plus/v1/";
	private final static String API_KEY = "AIzaSyBQC2ROstkIW5NBv0veYLjoBn5zy3j0HaE";
	private final static String ACTIVITIES_QUERY = "/activities/public";
	private Receiver<String> logger;
	private Adapter adapter;
	
	/**
	 * Interface for any list adapter that sets data from the posts into a view.
	 */
	public interface Adapter extends ListAdapter {
		public void setPosts(ArrayList<Post> posts);
	}
	
	public GooglePlusPresenter(Receiver<String> logger, Adapter adapter) {
		this.logger = logger;
		this.adapter = adapter;
	}
	
	public GooglePlusPresenter(Adapter adapter) {
		this(null, adapter);
	}
	
	public void updateFeedWithUser(String gplusId) {
		parsePosts(performHttpQuery(getActivityQuery(gplusId)));
	}
	
	private String performHttpQuery(String query){
		String qResult = null;
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(query);
		try {
			HttpEntity httpEntity = httpClient.execute(httpGet).getEntity();
			if (httpEntity != null){
				InputStream inputStream = httpEntity.getContent();
				Scanner lineScanner = new Scanner(inputStream);
				StringBuilder stringBuilder = new StringBuilder();
				while (lineScanner.hasNext()) {
					stringBuilder.append(lineScanner.next());  
				}
				qResult = stringBuilder.toString();
			}
		} catch (ClientProtocolException e) {
			logger.accept(e.getMessage());
		} catch (IOException e) {
			logger.accept(e.getMessage());
		}
		return qResult; 
	}

	private void parsePosts(String response) {
		if (response != null) {
			try {
				JSONObject obj = new JSONObject(response);
				JSONArray items = obj.getJSONArray("items");
				ArrayList<Post> posts = new ArrayList<Post>(items.length());
				for (int i = 0; i < items.length(); i++) {
					JSONObject post = items.getJSONObject(i);
					String displayName = post.getJSONObject("actor").getString("displayName");
					posts.add(new Post(displayName, post.getString("title")));
				}
				adapter.setPosts(posts);
			} catch (JSONException e) {
				logger.accept(e.getMessage());
			} 
		} 
	}
	
	public static String getActivityQuery(String gplusId) {
		return APPS_URL + "people/" + gplusId + ACTIVITIES_QUERY + "?key=" + API_KEY;
	}
	
	public static String getPersonQuery(String gplusId) {
		return APPS_URL + "people/" + gplusId + "?key=" + API_KEY;
	}
}
